#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@NAME          : user_route.py
@TIME          : 2025/03/02 10:00:00
@AUTHOR        : chenlip
@VERSION       : 0.1.0
@DESCRIPTION   : 用户路由视图，包括用户注册、登录等功能
'''

import datetime

from flask import Blueprint, g, request, render_template, redirect, url_for, flash, session, abort
from flask import current_app, jsonify

from flask_login import login_user, logout_user, login_required, current_user
from flask_jwt_extended import create_access_token, create_refresh_token, jwt_required, get_jwt_identity

from app.service.user_service import UserService
from app.service.avatar_service import AvatarService # 导入头像服务
from app.service.validate_data import ValidateData # 导入数据验证服务
from app.service.sse_notifi import NotificationService # 导入SSE通知服务
from app.middlewares.error_handler import route_exceptions, BusinessError

from app.common.utils import Utils as ut

profile_bp = Blueprint('profile', __name__, url_prefix='/profile')

@profile_bp.route('/profile', methods=['GET'])
@login_required
@route_exceptions
def profile():
    """用户个人资料页面"""
    # 获取当前用户对象

    # query_params = {
    #     'action_type': 1, # 登录动作
    #     'start_time': '2025-01-01',
    #     'end_time': '2025-12-31',
    #     'limit': 5,
    #     'desc': True
    # }
    
    # # 获取用户的额外信息（例如最近登录记录）
    # user_log_action = UserService.get_user_log_action(current_user.user_id, query_params)
    
    # 获取用户的统计信息
    # user_profile = UserService.get_user_profile(current_user.user_id)
    
    return render_template(
        'bbs/profile/profile.html',
        user=current_user
    )

@profile_bp.route('/update_profile', methods=['POST'])
@login_required
@route_exceptions
def update_profile():
    """更新用户个人资料, 不含密码"""
    # 获取已清洗的表单数据
    form_data = ValidateData.get_sanitized_form(request)
    
    # 验证个人资料数据
    is_valid, message = ValidateData.validate_profile_data(form_data)
    if not is_valid:
        raise BusinessError(message)
    
    # 准备更新数据
    update_data = {
        'nickname': form_data.get('nickname'),
        'email': form_data.get('email'),
        'phone': form_data.get('phone'),
        'qq': form_data.get('qq'),
        'birthday': form_data.get('birthday'),
        'user_sex': form_data.get('user_sex'),
        'real_name': form_data.get('real_name'),
        'id_card': form_data.get('id_card'),
        'description': form_data.get('description')
        # 其他可更新字段
    }
    
    # 过滤掉空值
    update_data = {k: v for k, v in update_data.items() if v is not None}
    
    # 调用用户服务进行更新
    result = UserService.update_profile(current_user.user_id, update_data)
    
    if result['success']:

        flash('flash- 个人资料更新成功', 'success')
        return redirect(url_for('profile.profile'))
    else:
        mess = result.get('message', '更新失败')
        raise BusinessError(result.get('message', '更新失败'))

@profile_bp.route('/upload_avatar', methods=['POST'])
@login_required
@route_exceptions
def upload_avatar():
    """上传用户头像"""
    if 'avatar' not in request.files:
        return jsonify({"success": False, "message": "未提供头像文件"}), 400
    
    avatar_file = request.files['avatar']
    
    if not avatar_file or avatar_file.filename == '':
        return jsonify({"success": False, "message": "未选择头像文件"}), 400
    
    # 验证文件类型
    if not ut.is_image_file(avatar_file):
        return {
            "success": False, 
            "message": "不支持的文件类型，只支持jpg、jpeg、png、gif和ico格式",
            "code": 415  # Unsupported Media Type
        }
    
    # 验证文件大小
    if not ut.check_file_size(avatar_file, 5):
        return {
            "success": False, 
            "message": f"文件大小超过限制，最大支持5MB",
            "code": 413  # Payload Too Large
        }
    
    # 使用头像服务上传文件
    avatar_result = AvatarService.upload_avatar(avatar_file, current_user.user_id)
    
    if not avatar_result['success']:
        return jsonify(avatar_result), 400
    
    # 更新用户头像URL
    avatar_url = avatar_result['data']['avatar_url']
    update_result = UserService.update_avatar(current_user.user_id, avatar_url)

    template_data = {} # 返回的数据
    
    if update_result['success']:
        flash('头像上传成功', 'success')

        template_data = {
            "success": True, 
            "message": "头像上传成功", 
            "avatar_url": avatar_url
        }

    else:
        flash('头像更新失败', 'error')
        template_data = {
            "success": False, 
            "message": update_result.get('message', '头像更新失败'),
            "avatar_url": None
        }

    _render_template = render_template('bbs/profile/profile.html', data=template_data)

    return _render_template

@profile_bp.route('/change_password', methods=['GET', 'POST'])
@login_required
@route_exceptions
def change_password():
    """修改密码路由"""
    # 处理GET请求 - 显示修改密码表单页面
    if request.method == 'GET':
        return render_template('bbs/profile/change_password.html', user_id=current_user.user_id)
    
    # 获取已清洗的表单数据
    form_data = ValidateData.get_sanitized_form(request)
    
    # 准备修改密码数据
    password_data = {
        'old_password': form_data.get('old_password'),
        'new_password': form_data.get('new_password')
    }
    
    # 调用用户服务进行修改密码
    result = UserService.change_password(current_user.user_id, password_data)
    
    if result['success']:
        flash('密码修改成功，请重新登录', 'success')
        return redirect(url_for('user.logout'))
    else:
        raise BusinessError(result.get('message', '密码修改失败'))
